const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const compression = require('compression');
const rateLimit = require('express-rate-limit');

const config = require('./config');
const connectDB = require('./config/database');
const errorHandler = require('./middleware/errorHandler');

// 路由
const authRoutes = require('./routes/auth');
const projectRoutes = require('./routes/projects');
const sectionRoutes = require('./routes/sections');
const formRoutes = require('./routes/forms');
const fieldTypeRoutes = require('./routes/fieldTypes');
const userRoutes = require('./routes/users');
const uploadRoutes = require('./routes/uploads');

// 保留原有的 DOCX 生成功能
const docx = require("docx");
const fs = require("fs");
const path = require("path");
const { generateSections } = require('./renderers/sections');
const { generateTableOfContents } = require('./renderers/tableOfContents');
const { Project, Form } = require('./models');

const {
    Document,
    Paragraph,
    TextRun,
    AlignmentType,
    Header,
    HeadingLevel,
    PageOrientation,
} = docx;

const app = express();

// 连接数据库
connectDB();

// 安全中间件
app.use(helmet());

// CORS
app.use(cors({
  origin: config.cors.origin,
  credentials: true
}));

// 限流 - 区分开发和生产环境
const limiter = rateLimit({
  windowMs: config.rateLimit.windowMs,
  max: config.nodeEnv === 'development' ? 1000 : config.rateLimit.maxRequests, // 开发环境放宽限制
  message: {
    success: false,
    message: '请求过于频繁，请稍后再试'
  },
  standardHeaders: true,
  legacyHeaders: false,
  skip: (req) => {
    // 开发环境跳过限流
    return config.nodeEnv === 'development';
  }
});

// 只在生产环境应用限流
if (config.nodeEnv !== 'development') {
  app.use('/api/', limiter);
}

// 日志
if (config.nodeEnv === 'development') {
  app.use(morgan('dev'));
} else {
  app.use(morgan('combined'));
}

// 压缩
app.use(compression());

// 解析请求体
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 静态文件（为图片开放跨源资源策略以便前端预览）
app.use('/uploads', (req, res, next) => {
  // 允许跨源嵌入资源（修复浏览器 NotSameOrigin 阻断图片预览）
  res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
  next();
}, express.static('uploads'));

// API 路由
app.use('/api/auth', authRoutes);
app.use('/api/projects', projectRoutes);
app.use('/api', sectionRoutes);
app.use('/api', formRoutes);
app.use('/api/field-types', fieldTypeRoutes);
app.use('/api/users', userRoutes);
app.use('/api', uploadRoutes);

// 保留原有的 DOCX 生成接口
app.post('/api/createDocx', async (req, res) => {
    try {
        const data = req.body;
        console.log(data,'data',req.body)
        if (!data) {
            return res.status(400).json({ error: 'Form data is required' });
        }

        // 如果没有传入数据，使用默认的 data.json 模版
        let documentData = data;
        if (!data.configSections && !data.sections) {
            try {
                const defaultData = JSON.parse(fs.readFileSync(path.join(__dirname, 'data.json'), 'utf8'));
                documentData = defaultData;
            } catch (error) {
                console.warn('Could not load default data.json, using provided data');
            }
        }

        // 读取页面方向设置（默认 portrait）
        const orientationStr = documentData?.pageSettings?.orientation === 'landscape' ? 'landscape' : 'portrait';
        const orientationEnum = orientationStr === 'landscape' ? PageOrientation.LANDSCAPE : PageOrientation.PORTRAIT;

        // 创建文档，使用渲染器生成内容
        const sections = documentData.configSections || documentData.sections || [];
        console.log('Processing sections:', sections.length);

        // 读取项目前置页（如果传入了项目ID）
        let frontMatter = [];
        try {
            const projectId = documentData._id || documentData.id;
            if (projectId) {
                const project = await Project.findById(projectId).select('frontMatter');
                if (project && Array.isArray(project.frontMatter) && project.frontMatter.length > 0) {
                    // 查询对应表单
                    const fm = [...project.frontMatter].sort((a,b)=> (a.order||0)-(b.order||0));
                    const fmFormIds = fm.map(i => i.formId);
                    const fmForms = await Form.find({ _id: { $in: fmFormIds } }).select('name config');

                    // 构造成“无章节标题”的 section 片段
                    const fmSectionsInput = [{
                        name: 'front-matter',
                        forms: fm.map(item => {
                            const form = fmForms.find(f => String(f._id) === String(item.formId));
                            if (!form) return null;
                            const cfg = JSON.parse(JSON.stringify(form.config || {}));
                            cfg.formConfig = cfg.formConfig || {};
                            // 将前置页属性注入到渲染配置
                            if (item.hideFormTitle !== undefined) cfg.formConfig.hideTitle = !!item.hideFormTitle;
                            if (item.pageBreakAfter !== undefined) cfg.formConfig.pageIsolation = !!item.pageBreakAfter;
                            return { _id: form._id, name: form.name, config: cfg };
                        }).filter(Boolean)
                    }];

                    // 复用现有渲染器（作为普通章节），但前置页不显示章节编号标题：
                    // 这里采用简单策略：渲染后移除开头的“Heading1”标题段落；
                    // 为避免复杂遍历，我们在 sections 渲染前将其视为一个虚拟章节，随后在结果中丢弃第一段标题。
                    const fmRendered = generateSections(fmSectionsInput);
                    // fmRendered 只有一个 section，移除首个段落（章节标题）
                    if (fmRendered.length > 0 && fmRendered[0].children && fmRendered[0].children.length > 0) {
                        // 移除第一段（章节标题）
                        fmRendered[0].children = fmRendered[0].children.slice(1);
                    }
                    frontMatter = fmRendered;
                }
            }
        } catch (e) {
            console.warn('读取前置页失败，继续生成正文:', e?.message || e);
        }

        // 生成所有sections（正文）
        const generatedSections = generateSections(sections);
        
        // 创建第一个section包含目录和头部信息
        const firstSection = {
            properties: {
                page: {
                    size: {
                        orientation: orientationEnum
                    }
                }
            },
            headers: {
                default: new Header({
                    children: [
                        new Paragraph({
                            alignment: AlignmentType.CENTER,
                            children: [
                                new TextRun(`方案编号：${documentData.name || 'XXXX'}`),
                                new TextRun({ text: "    " }),
                                new TextRun(`版本号：${documentData.version || '1.0'}`),
                                new TextRun({ text: "    " }),
                                new TextRun(`版本日期：${new Date().toLocaleDateString('zh-CN')}`),
                            ]
                        })
                    ]
                })
            },
            children: [
                // 生成目录页面
                ...generateTableOfContents(sections),
            ],
        };
        
        // 合并：前置页 → 目录/头部 → 正文
        const allSections = [...frontMatter, firstSection, ...generatedSections];
        
        const doc = new Document({
            sections: allSections,
            styles: {
                default: {
                    document: {
                        run: {
                            font: "SimSun",
                            size: 21,
                            language: {
                                eastAsia: "zh-CN"
                            }
                        }
                    }
                },
                paragraphStyles: [
                    {
                        id: "Heading1",
                        name: "Heading 1",
                        basedOn: "Normal",
                        next: "Normal",
                        quickFormat: true,
                        run: {
                            font: "SimSun",
                            size: 28,
                            bold: true,
                            color: "000000",
                        },
                        paragraph: {
                            spacing: { before: 400, after: 200 },
                            outlineLevel: 0,
                        },
                    },
                    {
                        id: "Heading2", 
                        name: "Heading 2",
                        basedOn: "Normal",
                        next: "Normal",
                        quickFormat: true,
                        run: {
                            font: "SimSun",
                            size: 24,
                            bold: true,
                            color: "000000",
                        },
                        paragraph: {
                            spacing: { before: 200, after: 100 },
                            outlineLevel: 1,
                        },
                    },
                    {
                        id: "TOCHeading",
                        name: "TOC Heading",
                        basedOn: "Normal",
                        next: "Normal",
                        run: {
                            font: "SimSun",
                            size: 32,
                            bold: true,
                            color: "000000",
                        },
                        paragraph: {
                            alignment: AlignmentType.CENTER,
                            spacing: { before: 400, after: 400 },
                        },
                    }
                ]
            }
        });

        // 生成文档buffer
        const buffer = await docx.Packer.toBuffer(doc);

        // 设置响应头
        res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
        
        // 处理文件名的中文字符编码
        const filename = documentData.name || 'document';
        const encodedFilename = encodeURIComponent(filename);
        res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${encodedFilename}.docx`);
        
        // 发送文件
        res.send(buffer);
    } catch (error) {
        console.error('Error generating DOCX:', error);
        res.status(500).json({ error: 'Failed to generate DOCX file' });
    }
});

// 健康检查
app.get('/health', (req, res) => {
  res.json({
    success: true,
    message: 'Server is running',
    timestamp: new Date().toISOString(),
    environment: config.nodeEnv
  });
});

// 404 处理
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    message: '接口不存在'
  });
});

// 错误处理中间件
app.use(errorHandler);

const PORT = config.port;

const server = app.listen(PORT, () => {
  console.log(`
🚀 Server running in ${config.nodeEnv} mode on port ${PORT}
📡 Health check: http://localhost:${PORT}/health
📚 API Base URL: http://localhost:${PORT}/api
  `);
});

// 优雅关闭
process.on('unhandledRejection', (err) => {
  console.error('Unhandled Promise Rejection:', err);
  server.close(() => {
    process.exit(1);
  });
});

process.on('SIGTERM', () => {
  console.log('SIGTERM received');
  server.close(() => {
    console.log('Process terminated');
  });
});

module.exports = app;